package t10086.WorkThread;
import t10086.Configure.InitConfig;
import t10086.Controller.DeliveryRecordController;
import t10086.Model.Messages.Message;
import t10086.WorkThread.Shared.ClientMap;

import java.net.InetSocketAddress;
import java.util.LinkedList;
import java.util.Queue;

public class MsgConvertHandler implements Runnable {
    //这个线程负责处理所有接收到的信息，进行移交
    private final Queue<Message> queue;
    public MsgConvertHandler(LinkedList<Message> queue) {
        this.queue = queue;
    }
    public static InetSocketAddress socketAddress = new InetSocketAddress(InitConfig.selfIp, 4400);
    @Override
    public void run() {
        while(!queue.isEmpty()&&!Thread.interrupted()){

            Message message = queue.poll();
            if (message != null) {
                switch (message.getType()){
                    case BROADCAST:
                            ClientMap.getClient(message.getReceiver()).putMessage(message);
                        break;
                    case RESPONSE:
                        if(message.getReceiver().equals(socketAddress)){
                            MsgProcessHandler.putMessage(message);
                        }else{
                            ClientMap.getClient(message.getReceiver()).putMessage(message);
                        }
                        break;
                    case REGISTER,ROBOT_UPLOAD,STATUS_EXCHANGE,REST_ROBOT_REQUEST:
                        MsgProcessHandler.putMessage(message);//交给它来处理
                        break;
                    case ORDER_SUBMIT:
                        System.out.println(message);
                        DeliveryRecordController.putMessage(message);
                        break;
                    default:
                        System.out.println("MessageType Error! "+message);//
                        break;
                }
            }
        }
    }
}
